﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.BLL;
using WXYW.DAL;

namespace WXYW
{
    public partial class ConfirmQuatationForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitialPage();
            }
        }

        #region 页面初始化绑定
        private void InitialPage()
        {
            BindApplicationForm();
            BindApplicationProduct();
            createLinkButton.NavigateUrl = string.Format("Quatation.aspx?{0}={1}", Constants.QUERYSTR_APPLICATION_ID, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
        }

        private void BindApplicationForm()
        {
            try
            {
                ApplicationService service = new ApplicationService();
                ApplicationForm form = service.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
                foreach (ApplicationProduct product in form.ApplicationProduct)
                {
                    if (!product.QuatationForm.IsLoaded)
                    {
                        product.QuatationForm.Load();
                    }
                }

                // for tip message 如果还有没有操作过的产品显示这个信息
                if (form.ApplicationProduct.Where(p => p.BLXX == null).Count() > 0)
                {
                    tipLabel.Text = "重要提示：此单还有产品尚未进行任何检查处理，请确认未处理产品不会产生报价，再慎重一次性报价给客户。";
                    tipLabel.Visible = true;
                }

                double totalPrice = 0;
                //List<ApplicationProduct> quationprodcuts = form.ApplicationProduct.Where(p => p.QuotationDateTime.HasValue && !p.ConfirmQuotationDateTime.HasValue).ToList();
                List<ApplicationProduct> quationprodcuts = form.ApplicationProduct.Where(p => p.QuotationDateTime.HasValue).ToList();
                ApplicationProductService applicationProductService = new ApplicationProductService();
                if (!form.QuatationDatetime.HasValue)
                {
                    foreach (ApplicationProduct quotateProduct in quationprodcuts)
                    {
                        foreach (QuatationForm quatationForm in quotateProduct.QuatationForm)
                        {
                            if (!(quatationForm.IsBWBA.HasValue && quatationForm.IsBWBA.Value))
                            {
                                totalPrice += quatationForm.Cost;
                            }
                        }
                        quotateProduct.Cost = totalPrice;
                        applicationProductService.UpdateProduct(quotateProduct);
                    }
                }
                rmaLabel.Text = form.ApplicationCode;
                userNameLabel.Text = form.User.FullName;
                receiveTimeLabel.Text = Convert.ToDateTime(form.ReceiveDateTime).ToString("yyyy-MM-dd");
                quatationLabel.Text = Convert.ToDateTime(form.QuatationDatetime).ToString("yyyy-MM-dd");
                contectPersonLabel.Text = form.User.ContactPerson;
                contectPhoneLabel.Text = form.User.UserPhone;
                distributeLabel.Text = Convert.ToDateTime(form.DistributeDateTime).ToString("yyyy-MM-dd");

                receiverLbl.Text = form.User.UserEmail;
                contactLbl.Text = form.User.ContactPerson;
                mobilePhoneLbl.Text = form.User.UserMobilePhone;

                SMSTxtBox.Text = string.Format("神州数码网络客服中心提示 尊敬的{0}客户您好，您送修的RMA NO.{1}过保产生维修费用{2}元，请尽快确认是否维修，神州数码客服中心 01082707718",
                    form.User.ContactPerson, form.ApplicationCode, totalPrice);
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "ConfirmQuatationForm::BindApplicationForm");
                throw ex;
            }
        }

        private void BindApplicationProduct()
        {
            ApplicationProductService service = new ApplicationProductService();
            applicationProductGridView.DataSource = service.GetQuatationProducts(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
            applicationProductGridView.DataBind();
        }

        protected void applicationProductGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                ((Label)e.Row.FindControl("IDLbl")).Text = (e.Row.RowIndex + 1).ToString();
                ConfirmQuatationProductModel model = e.Row.DataItem as ConfirmQuatationProductModel;
                RadioButtonList radioList = e.Row.FindControl("confirmMaintainRadioButtonList") as RadioButtonList;

                if (model.isConfirmRepair != null)
                {
                    if (model.isConfirmRepair == true)
                    {
                        radioList.SelectedIndex = 0;
                    }
                    else
                    {
                        radioList.SelectedIndex = 1;
                    }
                }
                else
                {
                    if (model.ApplySpecialService)
                    {
                        radioList.SelectedIndex = 2;
                    }
                    else
                    {
                        radioList.SelectedIndex = 4;
                    }
                }
            }
        }
        #endregion

        protected void confirmMaintainRadioButtonList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                RadioButtonList list = sender as RadioButtonList;
                GridViewRow row = (GridViewRow)list.NamingContainer;
                HiddenField producthf = row.FindControl("hfProductID") as HiddenField;
                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetApplicationProductByID(long.Parse(producthf.Value));
                if (!product.QuatationForm.IsLoaded)
                {
                    product.QuatationForm.Load();
                }
                // 客户确认维修
                if (list.SelectedIndex == 0)
                {
                    product.Cost = 0;
                    foreach (QuatationForm qform in product.QuatationForm)
                    {
                        product.Cost += qform.Cost;
                    }
                    product.IsDecideToRepair = true;
                    product.ConfirmQuotationDateTime = DateTime.Now;
                    service.UpdateProduct(product);
                }
                // 客户确认不维修
                else if (list.SelectedIndex == 1)
                {
                    RMALabel1.Text = product.ApplicationForm.ApplicationCode;
                    VersionNOLbl.Text = product.ProductVersionNumber;
                    reasonSerialLabel.Text = product.ProductSerialNumber;

                    ModalPopupExtender1.Show();
                    hfNotRepairProductID.Value = producthf.Value;
                }
                // 申请特服
                else if (list.SelectedIndex == 2)
                {
                    product.ConfirmQuotationDateTime = null;
                    product.IsDecideToRepair = null;

                    SpecialServiceService specialService = new SpecialServiceService();
                    specialService.AddSpecialServiceApplication(product);
                }
                // 驳回
                else if (list.SelectedIndex == 3)
                {
                    product.Status = "报价驳回-待修";
                    product.IsQuotePrice = null;
                    product.IsDecideToRepair = null;
                    product.QuotationDateTime = null;
                    product.Cost = 0;
                    product.ConfirmQuotationDateTime = null;
                    service.DeleteQuatationFormByProductID(long.Parse(producthf.Value));
                    service.UpdateProduct(product);

                    if (!product.ApplicationFormReference.IsLoaded)
                    {
                        product.ApplicationFormReference.Load();
                    }
                    if (!product.ApplicationForm.ApplicationProduct.IsLoaded)
                    {
                        product.ApplicationForm.ApplicationProduct.Load();
                    }
                    //if (product.ApplicationForm.ApplicationProduct.Where(p => p.QuatationForm.Count() > 0).Count() == 0)
                    //{
                        product.ApplicationForm.QuatationDatetime = null;
                        product.ApplicationForm.ConfirmQuatationCompleteDate = null;
                    //}
                    ApplicationService applicationService = new ApplicationService();
                    applicationService.UpdateApplication(product.ApplicationForm);
                }
                // 待确定
                else
                { 

                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "ConfirmQuatationForm.aspx.cs -> confirmMaintainRadioButtonList_SelectedIndexChanged");
                Response.Write(string.Format("<script language='JavaScript'> alert( '网络错误，稍后重试！');</script> "));
            }
        }

        // 不维修原因对话框
        protected void saveReasonLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetApplicationProductByID(long.Parse(hfNotRepairProductID.Value));
                product.ReasonOfNotRepair = reasonTextBox.Text;
                product.IsDecideToRepair = false; // 2013.09.05 添加
                product.ConfirmQuotationDateTime = DateTime.Now; // 2013.09.05 添加

                product.Status = "待修";
                if (!product.UpgradeForm.IsLoaded)
                {
                    product.UpgradeForm.Load();
                }
                if (!product.ReturnToFactoryForm.IsLoaded)
                {
                    product.ReturnToFactoryForm.Load();
                }
                // 升级并返厂的单子
                if (product.UpgradeForm.Count > 0 &&
                    product.ReturnToFactoryForm.Count > 0)
                {
                    ReturnToFactoryService returnToFactoryService = new ReturnToFactoryService();
                    ReturnToFactoryForm returnToFactoryForm = product.ReturnToFactoryForm.FirstOrDefault();
                    returnToFactoryForm.DoesRepair = false;
                    returnToFactoryForm.ConfirmQuatationDate = DateTime.Now;
                    returnToFactoryForm.Status = "返厂-待收货确认";
                    returnToFactoryService.Update(returnToFactoryForm);
                    product.Status = "升级完毕-待修";
                }
                // 升级非返厂的单子
                else if (product.UpgradeForm.Count > 0)
                {
                    UpgradeForm upgradeForm = product.UpgradeForm.FirstOrDefault();
                    switch (upgradeForm.SendWay)
                    {
                        case "平台":
                            upgradeForm.Status = "升级-完毕待发货";
                            break;
                        case "客户":
                            upgradeForm.Status = "升级完毕";
                            upgradeForm.CompleteTime = DateTime.Now;
                            break;
                        default:
                            throw new Exception(string.Format("不正确的升级发货方式, UpgradeFormID:{0}", upgradeForm.ID));
                            break;
                    }
                }
                else if (product.ReturnToFactoryForm.Count > 0)
                {
                    ReturnToFactoryForm returnToFactoryForm = product.ReturnToFactoryForm.FirstOrDefault();
                    if (!returnToFactoryForm.ProviderQuatationDate.HasValue)
                    {
                        returnToFactoryForm.Status = "返厂-待收货确认";
                    }
                    else
                    {
                        returnToFactoryForm.Status = "返厂-待报价确认";
                    }
                    ReturnToFactoryService returnToFactoryService = new ReturnToFactoryService();
                    returnToFactoryService.Update(returnToFactoryForm);
                }
                service.UpdateProduct(product);
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "ConfirmQuatationForm::saveReasonLinkButton_Click");
                throw ex;
            }
        }        

        protected void saveLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                // 更新产品的状态
                ApplicationProductService productService = new ApplicationProductService();
                ApplicationService service = new ApplicationService();
                foreach (GridViewRow row in applicationProductGridView.Rows)
                {
                    HiddenField hf = row.FindControl("hfProductID") as HiddenField;
                    RadioButtonList rbList = row.FindControl("confirmMaintainRadioButtonList") as RadioButtonList;
                    // 客户确认维修
                    if (rbList.SelectedIndex == 0)
                    {
                        ApplicationProduct product = productService.GetApplicationProductByID(long.Parse(hf.Value));
                        if (!product.ReturnToFactoryForm.IsLoaded)
                        {
                            product.ReturnToFactoryForm.Load();
                        }

                        // 返厂的 ApplicationProduct 仍然保持“返厂中”状态
                        if (product.ReturnToFactoryForm.Count > 0)
                        {
                            ReturnToFactoryForm returnToFactoryForm = product.ReturnToFactoryForm.FirstOrDefault();
                            if (!returnToFactoryForm.ReturnToFactoryQuatation.IsLoaded)
                            {
                                returnToFactoryForm.ReturnToFactoryQuatation.Load();
                            }
                            // 工厂报价了
                            if (returnToFactoryForm.ReturnToFactoryQuatation.Count > 0)
                            {
                                returnToFactoryForm.Status = "返厂-待报价确认";
                            }
                            else
                            {
                                returnToFactoryForm.DoesRepair = true;
                                returnToFactoryForm.ConfirmQuatationDate = DateTime.Now;
                                returnToFactoryForm.Status = "返厂-待收货确认";
                            }
                            ReturnToFactoryService returnToFactoryService = new ReturnToFactoryService();
                            returnToFactoryService.Update(returnToFactoryForm);
                        }
                        // 正常流程的 或者 升级的
                        else
                        {
                            product.Status = "已确认-待修";
                        }
                        product.ReasonOfNotRepair = null;
                        productService.UpdateProduct(product);

                        #region 旧方法
                        //if (product.Status.Equals("报价确认中"))
                        //{
                        //    product.Status = "已确认-待修";
                        //}
                        //else if (product.Status.Equals("返厂-待客户报价确认"))
                        //{
                        //    ReturnToFactoryService fcService = new ReturnToFactoryService();
                        //    foreach (ReturnToFactoryForm fcForm in product.ReturnToFactoryForm)
                        //    {
                        //        if (!fcForm.ReturnToFactoryQuatation.IsLoaded)
                        //        {
                        //            fcForm.ReturnToFactoryQuatation.Load();
                        //        }
                        //        if (fcForm.ReturnToFactoryQuatation.Count == 0)
                        //        {
                        //            fcForm.DoesRepair = true;
                        //            fcForm.ConfirmQuatationDate = DateTime.Now;
                        //            if (!fcForm.Status.Equals("返厂-维修完毕"))
                        //            {
                        //                product.Status = "已确认-待修";
                        //            }
                        //            else
                        //            {
                        //                product.Status = "维修完毕待发货";
                        //            }
                        //            fcForm.Status = "返厂-待收货确认";
                        //        }
                        //        else
                        //        {
                        //            if (!fcForm.Status.Equals("返厂-维修完毕"))
                        //            {
                        //                product.Status = "已确认-待修";
                        //            }
                        //            else
                        //            {
                        //                product.Status = "维修完毕待发货";
                        //            }
                        //            fcForm.Status = "返厂-待报价确认";
                        //        }
                        //        fcService.Update(fcForm);
                        //    }
                        //}
                        #endregion
                    }
                    // 不维修
                    else if (rbList.SelectedIndex == 1)
                    {
                        ApplicationProduct product = productService.GetApplicationProductByID(long.Parse(hf.Value));
                        product.ConfirmQuotationDateTime = DateTime.Now;
                        product.IsDecideToRepair = false;
                        product.Status = "待修";
                        if (!product.UpgradeForm.IsLoaded)
                        {
                            product.UpgradeForm.Load();
                        }
                        if (!product.ReturnToFactoryForm.IsLoaded)
                        {
                            product.ReturnToFactoryForm.Load();
                        }
                        // 升级并返厂的单子
                        if (product.UpgradeForm.Count > 0 && 
                            product.ReturnToFactoryForm.Count > 0)
                        {
                            ReturnToFactoryService returnToFactoryService = new ReturnToFactoryService();
                            ReturnToFactoryForm returnToFactoryForm = product.ReturnToFactoryForm.FirstOrDefault();
                            returnToFactoryForm.DoesRepair = false;
                            returnToFactoryForm.ConfirmQuatationDate = DateTime.Now;
                            returnToFactoryForm.Status = "返厂-待收货确认";
                            returnToFactoryService.Update(returnToFactoryForm);
                            product.Status = "升级完毕-待修";
                        }
                        // 升级非返厂的单子
                        else if (product.UpgradeForm.Count > 0)
                        {
                            UpgradeForm upgradeForm = product.UpgradeForm.FirstOrDefault();
                            switch (upgradeForm.SendWay)
                            {
                                case "平台":
                                    upgradeForm.Status = "升级-完毕待发货";                                    
                                    break;
                                case "客户":
                                    upgradeForm.Status = "升级完毕";
                                    upgradeForm.CompleteTime = DateTime.Now;
                                    break;
                                default:
                                    throw new Exception(string.Format("不正确的升级发货方式, UpgradeFormID:{0}", upgradeForm.ID));
                                    break;
                            }
                        }
                        else if (product.ReturnToFactoryForm.Count > 0)
                        {
                            ReturnToFactoryForm returnToFactoryForm = product.ReturnToFactoryForm.FirstOrDefault();
                            if (!returnToFactoryForm.ProviderQuatationDate.HasValue)
                            {
                                returnToFactoryForm.Status = "返厂-待收货确认";
                            }
                            else
                            {
                                returnToFactoryForm.Status = "返厂-待报价确认";
                            }
                            ReturnToFactoryService returnToFactoryService = new ReturnToFactoryService();
                            returnToFactoryService.Update(returnToFactoryForm);
                        }
                        productService.UpdateProduct(product);

                        #region old code
                        //if (product.UpgradeForm.Where(u => u.Status != "升级-不同意").Count() > 0)
                        //{
                        //    if (product.UpgradeForm.FirstOrDefault().SendWay.Equals("平台"))
                        //    {
                        //        UpgradeForm upgradeform = product.UpgradeForm.FirstOrDefault();
                        //        upgradeform.Status = "升级-完毕待发货";
                        //        product.Status = "升级-完毕待发货";
                        //        product.RepairCompleteDateTime = DateTime.Now;
                        //    }
                        //    else
                        //    {
                        //        product.Status = "维修完毕待发货";
                        //        product.RepairCompleteDateTime = DateTime.Now;
                        //    }
                        //}
                        //else if (product.Status.Equals("返厂-待客户报价确认"))
                        //{
                        //    if (!product.ReturnToFactoryForm.IsLoaded)
                        //    {
                        //        product.ReturnToFactoryForm.Load();
                        //    }
                        //    ReturnToFactoryService returnService = new ReturnToFactoryService();
                        //    foreach (ReturnToFactoryForm returnForm in product.ReturnToFactoryForm)
                        //    {
                        //        returnForm.DoesRepair = false;
                        //        returnForm.Status = "返厂-待收货确认";
                        //        returnForm.ConfirmQuatationDate = DateTime.Now;
                        //        returnService.Update(returnForm);
                        //        product.Status = "维修完毕待发货";
                        //    }
                        //}
                        //else
                        //{
                        //    product.Status = "维修完毕待发货";
                        //    product.RepairCompleteDateTime = DateTime.Now;
                        //}
                        #endregion                        
                    }
                    // 驳回
                    else if (rbList.SelectedIndex == 3)
                    {
                        ApplicationProduct product = productService.GetApplicationProductByID(long.Parse(hf.Value));
                        product.Status = "报价驳回-待修";
                        product.IsQuotePrice = null;
                        product.IsDecideToRepair = null;
                        product.QuotationDateTime = null;
                        product.Cost = 0;
                        product.ConfirmQuotationDateTime = null;
                        productService.DeleteQuatationFormByProductID(long.Parse(hf.Value));
                        productService.UpdateProduct(product);

                        if (!product.ApplicationFormReference.IsLoaded)
                        {
                            product.ApplicationFormReference.Load();
                        }
                        if (!product.ApplicationForm.ApplicationProduct.IsLoaded)
                        {
                            product.ApplicationForm.ApplicationProduct.Load();
                        }
                        //if (product.ApplicationForm.ApplicationProduct.Where(p => p.QuatationForm.Count() > 0).Count() == 0)
                        //{
                            product.ApplicationForm.QuatationDatetime = null;
                            product.ApplicationForm.ConfirmQuatationCompleteDate = null;
                        //}
                        service.UpdateApplication(product.ApplicationForm);
                    }
                }

                ApplicationForm form = service.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
                if (form.QuatationDatetime.HasValue && form.ApplicationProduct.Where(p => p.QuotationDateTime.HasValue && !p.ConfirmQuotationDateTime.HasValue).Count() == 0)
                {
                    form.ConfirmQuatationCompleteDate = DateTime.Now;
                    service.UpdateApplication(form);

                    Response.Write(string.Format("<script language='JavaScript'> alert( '已成功保存！');location.href= 'ListFormConfirmQuatation.aspx' </script> "));
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息提交失败，还有产品报价未进行确认，请确认所有产品报价信息之后再进行提交。已确认的报价信息已经保存，如需稍后再确认，可点击返回退出当前页面。');"), true);
                }
                #region old code
                //更新申请单的状态      
                //ApplicationForm form = service.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                //if (!form.ApplicationProduct.IsLoaded)
                //{
                //    form.ApplicationProduct.Load();
                //}

                //if (service.IsFinishMaintain(form.ApplicationID))
                //{
                //    form.Status = "维修完毕待发货";
                //    service.UpdateApplication(form);
                //}
                //else
                //{
                //    if ((form.ApplicationProduct.Where(p => p.Status == "报价确认中" || p.Status.Equals("返厂-待客户报价确认")).Count() == 0)
                //        && form.ApplicationProduct.Where(p => p.IsDecideToRepair.HasValue && p.IsDecideToRepair == true).Count() > 0)
                //    {
                //        form.Status = "待付款确认";
                //        service.UpdateApplication(form);
                //        if (!form.UserReference.IsLoaded)
                //        {
                //            form.UserReference.Load();
                //        }
                //        EmailService.SendEmailToSKY(form.ApplicationCode, form.User.ContactPerson);
                //    }
                //    else if (form.ApplicationProduct.Count == form.ApplicationProduct.Where(p => p.IsQuotePrice == null).Count())
                //    {
                //        form.Status = "待修";
                //        form.QuatationDatetime = null;
                //        service.UpdateApplication(form);
                //    }
                //}
                #endregion                
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::saveLinkButton_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息提交时发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        private void ConfirmRepair()
        {
 
        }

        protected void sendSMSLnkBtn_Click(object sender, EventArgs e)
        {
            string retCode = SMSService.SendSMS(mobilePhoneLbl.Text, SMSTxtBox.Text);
            if (retCode == "0")
            {
                Response.Write(string.Format("<script language='JavaScript'> alert( '短信通知已经发送给客户！');location.href= '{0}?{1}={2}' </script> ", "ConfirmQuatationForm.aspx", Constants.QUERYSTR_APPLICATION_ID, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
            }
        }
    }
}
